package com.xx.bysj.aop;

import com.alibaba.fastjson.JSONArray;
import com.xx.bysj.BysjApplication;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.StringJoiner;

@Aspect
@Component
public class LogAopAspect {

    /**
     * 切面的切入点
     */
    @Pointcut(value = "@annotation(com.xx.bysj.aop.LogAop)")
    private void logAopPointcut() {
    }

    private static final Logger logger = LoggerFactory.getLogger(BysjApplication.class);

    /**
     * 日志操作
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("logAopPointcut()")
    public Object logOperate(ProceedingJoinPoint point) throws Throwable {
        Object obj = point.proceed();
        Object[] args = point.getArgs();
        //对象
        Object target = point.getTarget();
        String methodName = point.getSignature().getName();
        Class[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
        Method method = target.getClass().getMethod(methodName, parameterTypes);

        String actionName = method.getAnnotation(LogAop.class).actionName();
        String actionType = method.getAnnotation(LogAop.class).actionType();
        String[] argName = method.getAnnotation(LogAop.class).argName();
        //类名
        String className = target.getClass().getName();
        logger.info("类: " + className + ";方法: " + methodName + ";操作类型: " + actionType + ";操作描述: "
                + actionName + ";实体信息: " + JSONArray.toJSONString(argName));
        return obj;
    }


    /**
     * 获取方法类全名+方法名
     *
     * @param method 方法
     * @return 方法类全名+方法名
     */
    private String getClassAndMethodName(Method method) {
        //获取类全名
        String className = method.getDeclaringClass().getName();
        //获取方法名
        String methodName = method.getName();
        // 推荐使用StringJoiner替换builder和buffer
        StringJoiner stringJoiner = new StringJoiner(",");
        stringJoiner.add(className);
        stringJoiner.add(".");
        stringJoiner.add(methodName);

        return stringJoiner.toString();
    }

}
